package com.tianma315.admin.stock.rest;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.tianma315.admin.common.base.BaseController;
import com.tianma315.admin.common.exception.MessageException;
import com.tianma315.admin.common.utils.DateUtils;
import com.tianma315.admin.common.utils.ResponseUtil;
import com.tianma315.admin.common.utils.Result;
import com.tianma315.admin.material.domain.PurchaseDO;
import com.tianma315.admin.oss.domain.FileDO;
import com.tianma315.admin.oss.service.FileService;
import com.tianma315.admin.stock.domain.WarehousingRecord;
import com.tianma315.admin.stock.domain.vo.WarehousingRecordAndArrtVO;
import com.tianma315.admin.stock.domain.vo.WarehousingRecordFileVO;
import com.tianma315.admin.stock.domain.vo.WarehousingRecordVo;
import com.tianma315.admin.stock.service.StockService;
import org.apache.commons.lang.ArrayUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

//                   _ooOoo_
//                  o8888888o
//                  88" . "88
//                  (| -_- |)
//                  O\  =  /O
//               ____/`---'\____
//             .'  \\|     |//  `.
//            /  \\|||  :  |||//  \
//           /  _||||| -:- |||||-  \
//           |   | \\\  -  /// |   |
//           | \_|  ''\---/''  |   |
//           \  .-\__  `-`  ___/-. /
//         ___`. .'  /--.--\  `. . __
//      ."" '<  `.___\_<|>_/___.'  >'"".
//     | | :  `- \`.;`\ _ /`;.`/ - ` : | |
//     \  \ `-.   \_ __\ /__ _/   .-` /  /
//======`-.____`-.___\_____/___.-`____.-'======
//                   `=---='
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//         佛祖保佑       永无BUG

/**
 * 库存接口
 * <p>
 * Created by zcm on 2019/5/28.
 */
@RestController
@RequestMapping("/stock")
public class StockRestController extends BaseController {

    @Autowired
    private StockService stockService;

    @Autowired
    private FileService fileService;




    /**
     * 入库记录
     *
     * @param pageNumber
     * @param pageSize
     * @param searchKey
     * @return
     */
    @GetMapping("/list")
    Result list(int pageNumber, int pageSize, String searchKey) {
        Page<WarehousingRecordVo> page = stockService.getPage(pageNumber, pageSize, searchKey);
        if (page == null)
            return Result.fail();
        return Result.ok(page);
    }


    @GetMapping("/stockList")
    Result stockList(int pageNumber, int pageSize, String searchKey) {
        Page<WarehousingRecordVo> page = stockService.getPage(pageNumber, pageSize, searchKey);
        if (page == null)
            return Result.fail();
        return Result.ok(page);
    }


    @PostMapping("/add")
    @RequiresPermissions("stock:add")
    Result add(WarehousingRecordFileVO record) {
        String url = "";
        if (!record.getFile().isEmpty()){
            try {
                url = fileService.upload(record.getFile().getBytes(),record.getFile().getOriginalFilename());
            } catch (IOException e) {
                System.out.println(e.getMessage());
                throw new MessageException("文件上传异常");
            }
        }

        record.setCreateBy(getUserId());
        record.setCreateDate(new Date());
        record.setImgUrl(url);
        if (stockService.save(record))
            return Result.ok();
        return Result.fail();
    }

    @PostMapping("/update")
    Result update(WarehousingRecordFileVO record) {
        String url = "";
        if (!record.getFile().isEmpty()){
            try {
                url = fileService.upload(record.getFile().getBytes(),record.getFile().getOriginalFilename());
            } catch (IOException e) {
                System.out.println(e.getMessage());
                throw new MessageException("文件上传异常");
            }
        }
        record.setCreateBy(getUserId());
        record.setCreateDate(new Date());
        record.setStatus(WarehousingRecord.STATUS_ENABLE);
        record.setImgUrl(url);

        if (stockService.updateById(record)){
            stockService.updateStockById(record.getProductId(),record.getLastNum(),record.getNumber());
            return Result.ok();
        }


        return Result.fail();
    }


    @PostMapping("/revert")
    @RequiresPermissions("stock:revert")
    Result revert(long warehousingRecordId) {
        if (stockService.revert(warehousingRecordId))
            return Result.ok();
        return Result.fail();
    }

    @PostMapping("/batchRevert")
    @RequiresPermissions("stock:revert")
    Result revert(@RequestParam("ids[]")Long[] ids) {
        if (stockService.batchRevert(ids)){
            return Result.ok();
        }

        return Result.fail();
    }


    @PostMapping("/addReportImg/{warehousingRecordId}")
    @ResponseBody
    Result addReportImg(HttpServletRequest request, WarehousingRecord warehousingRecord){
        stockService.insertImg(request,warehousingRecord);
        return Result.ok();
    }

    @GetMapping("/deleteImg/{stat}/{warehousingRecordId}")
    @ResponseBody
    Result deleteImg(@PathVariable("stat")Integer stat,@PathVariable("warehousingRecordId")Integer warehousingRecordId){
        WarehousingRecord warehousingRecord = stockService.selectById(warehousingRecordId);
        String[] imgUrl = warehousingRecord.getImgUrl().split(",");
        imgUrl = (String[]) ArrayUtils.remove(imgUrl, stat-1);
        warehousingRecord = new WarehousingRecord();
        warehousingRecord.setWarehousingRecordId(warehousingRecordId);
        //System.out.println(imgUrl.length);
        if (imgUrl.length>0){
            String img="";
            for (int i = 0; i <imgUrl.length ; i++) {
                img += imgUrl[i]+",";
            }
            warehousingRecord.setImgUrl(img.substring(0,img.length()-1));
        }else{
            warehousingRecord.setImgUrl(null);
        }
        if (stockService.updateWareById(warehousingRecord)){
            return Result.ok();
        }
        return Result.fail();
    }

    /**
     * 导出模板
     */
    @GetMapping( "/exportStock")
    public void exportStock(HttpServletResponse response){
        String fileName = "产品导入模板.xls";
        try {
            response = ResponseUtil.getResponse(response,fileName);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        HSSFWorkbook wb =stockService.exportStock();
        try(OutputStream os = response.getOutputStream()) {
            wb.write(os);
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }



    /**
     * 导入excel
     */
    @ResponseBody
    @PostMapping( "/importStock")
    public Result importStock(MultipartFile file){
        if (!file.isEmpty()){
            stockService.importStock(file,getUserId());
        }
        return Result.ok();
    }


    /**
     * 查询入库记录的检测数据
     * @return
     */
    @PostMapping("/warehousingRecordAndArrtInfo")
    Result warehousingRecordAndArrtInfo(@RequestParam("pageNumber") int pageNumber,
                                        @RequestParam("pageSize")int pageSize,
                                        @RequestParam("productName") String productName,
                                        @RequestParam("beginDate") Date beginDate,
                                        @RequestParam("endDate") Date endDate) {
        Page<WarehousingRecordAndArrtVO> page =
                stockService.warehousingRecordAndArrtInfo(pageNumber,pageSize,productName, beginDate, endDate);
        if (page == null)
            return Result.fail();
        return Result.ok(page);
    }

    @GetMapping("/getDataJson")
    Result testJason(int pageNumber,
                     int pageSize,
                     String productName,
                     Date beginDate,
                     Date endDate) throws ParseException {
//        beginDate = DateUtils.formatDate("2019-06-10");
//        endDate = DateUtils.formatDate("2019-12-26");
        Page<JSONObject> page = stockService.getDataJson(pageNumber,pageSize,productName, beginDate, endDate);
        return Result.ok(page);
    }

    @GetMapping("/getHead")
    Result getHead() {
        List<JSONObject> list = stockService.getHead();
        return Result.ok(list);
    }

}
